package com.lib.util.image;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import com.qbw.log.XLog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author qbw
 * @createtime 2016/06/16 13:46
 */


public class ImageUtil {

    /**
     * @param uri
     * @return uri图片对应的路径
     */
    public static String getImagePath(Context context, Uri uri) {
        String selection = null;
        String[] selectionArgs = null;
        // Uri is different in versions after KITKAT (Android 4.4), we need to
        if (Build.VERSION.SDK_INT >= 19 && DocumentsContract.isDocumentUri(context.getApplicationContext(),
                                                                           uri)) {
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            } else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                uri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                                                 Long.valueOf(id));
            } else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("image".equals(type)) {
                    uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                selection = "_id=?";
                selectionArgs = new String[]{
                        split[1]
                };
            }
        }
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {
                    MediaStore.Images.Media.DATA
            };
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver()
                                .query(uri, projection, selection, selectionArgs, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
                e.printStackTrace();
                XLog.e(e);
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static List<String> getAllImagesPath(Context context) {
        return getAllImagesPath(context, null);
    }

    public static void getAllImagesPathAsync(final Context context, final CallBack callBack) {
        new Thread() {
            @Override
            public void run() {
                getAllImagesPath(context, callBack);
            }
        }.start();
    }

    /**
     * Getting All Images Path(以拍照时间降序排列)
     *
     * @param context
     * @param callBack 不为null则异步回调每一张图片的信息
     * @return List with images Path
     */
    private static List<String> getAllImagesPath(Context context, CallBack callBack) {

        List<String> imageInfoList = new ArrayList<>();

        int columnIndexData;

        String[] projection = {MediaStore.MediaColumns.DATA};

        Cursor cursor = context.getContentResolver()
                               .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                      projection,
                                      null,
                                      null,
                                      new String(MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC"));

        columnIndexData = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);

        while (cursor.moveToNext()) {
            String path = cursor.getString(columnIndexData);
            if (null != callBack) {
                callBack.onGetImageInfo(path);
            }
            imageInfoList.add(path);
        }

        return imageInfoList;
    }

    public static Point getLocalImageSize(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return new Point(0, 0);
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        return new Point(options.outWidth, options.outHeight);
    }

    public interface CallBack {
        void onGetImageInfo(String imagePath);
    }
}
